package com.netty.chatRoom.server.Handler;

import com.netty.chatRoom.message.GroupChatRequestMessage;
import com.netty.chatRoom.message.GroupChatResponseMessage;
import com.netty.chatRoom.server.session.GroupSession;
import com.netty.chatRoom.server.session.GroupSessionFactory;
import com.netty.chatRoom.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupChatRequestMessage groupChatRequestMessage) throws Exception {
        // 获取发送者
        String from = groupChatRequestMessage.getFrom();
        String groupName = groupChatRequestMessage.getGroupName();
        Set<String> groupMembers = GroupSessionFactory.getGroupSession().getMembers(groupName);
        if(groupMembers.size()==0) {
            channelHandlerContext.writeAndFlush(new GroupChatResponseMessage(false,String.format("【%s】群聊不存在",groupName)));
            return;
        };
        groupMembers.forEach((member)->{
            if(!member.equals(from)){
                Channel channel = SessionFactory.getSession().getChannel(member);
                if (channel!=null){
                    channel.writeAndFlush(new GroupChatResponseMessage(from,groupChatRequestMessage.getContent()));
                }
            }
        });
    }
}
